package org.langqiao.jvm.base;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ObjectPoolFactory {

	private Map<String , Object> objectPool = new HashMap<String ,Object>();
	
	private Object createObject(String clazzName) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
		//根据字符窜的类名来获取class对象
		Class<?> clazz = Class.forName(clazzName);
		//使用clazz对应的默认构造器创建实例
		return clazz.newInstance();
	}
	
	public void initPool(String fileName){
		FileInputStream fis =null ;
		try {
			fis = new FileInputStream(fileName);
			Properties prop = new Properties();
			prop.load(fis);
			for(String name:prop.stringPropertyNames()){
				objectPool.put(name, createObject(prop.getProperty(name)));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("读取：" + fileName + "发生异常");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}finally{
			if(fis != null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public Object getObject(String name){
		return objectPool.get(name);
	}
	public static void main(String[] args) {
		ObjectPoolFactory opf = new ObjectPoolFactory();
		opf.initPool("obj.txt");
		System.out.println(opf.getObject("a"));
	}

}
